<template>
  <div>
    <el-card shadow="never">
      <vxe-grid v-bind="gridOptions" ref="xGrid">
        <!-- 表单 start -->
         <template #deptCategory="{row}">
          <el-tag>{{row.deptCategoryName}}</el-tag>
        </template>
        <template #actionItem>
          <el-button
            color="#1E3485"
            size="small"
            icon="Edit"
            @click="EditDialogModal.open({type: 'add',row: {} ,})"
          >新建</el-button
          >
          <el-button
            size="small"
            color="#1E3485"
            icon="Search"
            @click="searchChange"
          >搜索</el-button
          >
          <el-button
            size="small"
            type="default"
            icon="Delete"
            @click="searchReset"
          >清空</el-button
          >
        </template>
        <!-- 表单 end -->

        <!-- 表格 start -->
        <template #menu="{ row }">
          <vxe-button
            type="text"
            size="small"
            @click="EditDialogModal.open({type: 'view',row,})"
          >
            查看
          </vxe-button>
          <vxe-button
            type="text"
            size="small"
            @click="EditDialogModal.open({type: 'edit',row,})"
          >
            编辑
          </vxe-button>
          <vxe-button
            type="text"
            size="small"
            @click="rowDel(row)"
          >
            删除
          </vxe-button>
          <vxe-button
            type="text"
            size="small"
            @click="EditDialogModal.open({type: 'add',row,})"
          >
            新增子项
          </vxe-button>
        </template>
        <!-- 表格 end -->
      </vxe-grid>
    </el-card>

    <EditDialog
      @register="EditDialogModal.register"
      @confirmRowAdd="rowAdd"
      @confirmRowEdit="rowEdit"
    />
  </div>
</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref} from 'vue'
  import type {VxeGridProps, VxeGridListeners, VxeFormInstance} from 'vxe-table'
  import EditDialog, {useEditDialog} from './components/EditDialog'
  import {getSettings} from "@/views/ERP_systemManage/dept/settings";
  import {getOrgList, deptAdd, deptUpdate, deptDelete} from "@/api/ERP_sales";
  import {ElMessage} from "element-plus";
  import {getDictDetail} from "@/api/utils";

  const instance = getCurrentInstance()
  const globalThis = instance.appContext.config.globalProperties

  const EditDialogModal = useEditDialog()

  const dept_levelOPTIONS = ref([])

// 前端分页
const getList = async (row?: any) => {
  if(gridOptions.loading) return
  gridOptions.loading = true
  let params: ApiParams = {
    ...gridOptions.formConfig.data,
  };
  if(row?.id) {
    params.parentId = row.id
  }

  try {
    if(!dept_levelOPTIONS.value.length){
      const { data: data1 } =  await getDictDetail({
        key: 'dept_level'
      })
      dept_levelOPTIONS.value = data1
    }

    const response: ApiResponse = await getOrgList(params);
    const data = response.data.map(v => {
      const deptLevel = dept_levelOPTIONS.value.find(t => +t.key === +v.deptLevel)
      return {
        ...v,
        deptLevelDesc: deptLevel?.value,
        children: [],
        parentName: row?.id && row?.deptName || '顶级',
      }
    });
    if(row?.id) {
      return Promise.resolve(data)
    }else {
      gridOptions.data = data
    }

  } catch (error) {
    console.log(error)
    ElMessage.error("获取表格数据失败");
  } finally {
    gridOptions.loading = false;
  }
}
const xGrid = ref<VxeFormInstance>()
const gridOptions = reactive<VxeGridProps>({
  ...getSettings(),
  treeConfig: {
    parentField: 'parentId',
    rowField: 'id',
    childrenField: 'children',
    lazy: true,
    hasChild: 'hasChildren',
    loadMethod ({ row }) {
      // 异步加载子节点
      return getList(row)
    }
  },
  data: [],
})

const searchChange = () => {
  getList()
}
const searchReset = () => {
  const $xGrid = xGrid.value
  const $form = $xGrid.getRefMaps().refForm.value
  if ($form) {
    $form.reset()
  }
  getList()
}

const rowAdd = async (form = {}, row = {}, done, loading) => {
 console.log(form, row)
  try {
    const {parentId,deptCategory, deptLevel, sort, shortName, deptCode, deptName } = form
    const { parentCode = 'ROOT' } = row
    const params = {
      parentCode,
      parentId: parentId || '0',
      deptCategory,
      deptLevel,
      sort,
      shortName,
      deptCode,
      deptName,
    }
    await deptAdd(params)
    done()
    getList()
  }catch (e) {
   console.log(e)
    loading()
  }
}
  const rowEdit = async (form = {},  row = {}, done, loading) => {
  console.log(form, row)
  try {
    const {parentId,deptCategory, deptLevel, sort, shortName, deptCode, deptName } = form
    const {parentCode,id } = row
    const params = {
      id,
      parentCode,
      parentId,
      deptCategory,
      deptLevel,
      sort,
      shortName,
      deptCode,
      deptName,
    }
    await deptUpdate(params)
    done()
    getList()
  }catch (e) {
    console.log(e)
    loading()
  }
}
  const rowDel = async (row) => {
    try {
      await globalThis.$confirm(
        `确认删除选中的数据吗？`,
        {
          title: '提示',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      await deptDelete({
        id: row.id
      })
      globalThis.$message.success('删除成功')
      getList()
    } catch (e) {
      console.log(e)
    }
  }
getList()
</script>
